package cn.freeprogrammer.igen.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import cn.freeprogrammer.igen.Globals;
import cn.freeprogrammer.igen.data.DaoData;
import cn.freeprogrammer.igen.data.EntityData;
import cn.freeprogrammer.igen.data.ProjectData;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * DAO生成器.
 * 
 * @author minwh
 *
 */
public class DaoGenerator implements IGenerator {
	private ProjectData projectData;	
	private String baseDaoName;	
	private String fullBaseDaoName;
	private Template tpl;

	public DaoGenerator(ProjectData projectData) throws Exception {
		this.projectData = projectData;
		baseDaoName = "IBatisEntityDao";
		fullBaseDaoName = projectData.getBasePackage() + ".framework.orm.ibatis." + baseDaoName;

		// load sqlmap template
		Configuration cfg = new Configuration();
		cfg.setDirectoryForTemplateLoading(new File(getClass().getResource(Globals.TPL_DIRECTORY)
				.getFile()));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		tpl = cfg.getTemplate(Globals.DAO_TPL);
		
		// create dao base dir
		new File(projectData.getDaoBasePath()).mkdirs();
	}
	
	public void generate() throws Exception {
		if (!projectData.isGenerateDao()) {
			return;
		}
		
		for (EntityData entityData : projectData.getEntityDatas()) {
			generate(entityData);
		}
	}
	
	private void generate(EntityData entityData) throws Exception {
		DaoData daoData = new DaoData(entityData, projectData.getDaoPackage());

		Map model = new HashMap();
		model.put("metadata", daoData);
		model.put("baseDaoName", baseDaoName);
		model.put("fullBaseDaoName", fullBaseDaoName);

		String filePath = getDaoFilePath(daoData);
		File file = new File(filePath);
		file.getParentFile().mkdirs();
		file.createNewFile();
		
		Writer out = new FileWriter(file);
		tpl.process(model, out);
		out.flush();
	}

	private String getDaoFilePath(DaoData daoData) {
		String daoFilePath = projectData.getDaoBasePath() + "/"
				+ daoData.getFullDaoName().replaceAll("\\.", "/") + ".java";
		return daoFilePath;
	}
}
